package com.cskaoyan.service.mallservice;

import com.cskaoyan.Utils.WxOrderStatusUtils;
import com.cskaoyan.bean.cart.Cart;
import com.cskaoyan.bean.cart.CartExample;
import com.cskaoyan.bean.goods.GoodsComment;
import com.cskaoyan.bean.goods.GoodsProduct;
import com.cskaoyan.bean.goods.GoodsProductExample;
import com.cskaoyan.bean.promotebean.Coupon;
import com.cskaoyan.bean.promotebean.CouponExample;
import com.cskaoyan.bean.promotebean.CouponUser;
import com.cskaoyan.bean.promotebean.CouponUserExample;
import com.cskaoyan.bean.userbean.Address;
import com.cskaoyan.bean.userbean.AddressExample;
import com.cskaoyan.bean.userbean.User;
import com.cskaoyan.bean.mallbean.Order;
import com.cskaoyan.bean.mallbean.OrderExample;
import com.cskaoyan.bean.mallbean.OrderGoods;
import com.cskaoyan.bean.mallbean.OrderGoodsExample;
import com.cskaoyan.mapper.cart.CartMapper;
import com.cskaoyan.mapper.goodsmapper.GoodsCommentMapper;
import com.cskaoyan.mapper.goodsmapper.GoodsProductMapper;
import com.cskaoyan.mapper.promotemapper.CouponMapper;
import com.cskaoyan.mapper.promotemapper.CouponUserMapper;
import com.cskaoyan.mapper.usermapper.AddressMapper;
import com.cskaoyan.mapper.usermapper.UserMapper;
import com.cskaoyan.mapper.mallmapper.OrderGoodsMapper;
import com.cskaoyan.mapper.mallmapper.OrderMapper;
import com.cskaoyan.vo.mallvo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author hsp
 * @date 2021/5/10 16:08
 */
@Service
public class OrderServiceImpl  implements OrderService{
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    GoodsCommentMapper goodsCommentMapper;
    /**
     page: 1
     limit: 20
     orderStatusArray: 103
     orderStatusArray: 201
     sort: add_time
     order: desc
     userId: 1
     orderSn: 20210424759808
     */
    @Override
    public OrderListVo queryOrder(Integer page, Integer limit, Integer[] orderStatusArray, String sort, String order, Integer userId, String orderSn) {
//        分页
        PageHelper.startPage(page,limit);
//        条件查询订单
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        if (userId!=null)
            criteria.andUserIdEqualTo(userId);
        if (orderSn!=null && !orderSn.equals(""))
            criteria.andOrderSnEqualTo(orderSn);

        if (orderStatusArray!=null){
            List<Integer> orderStatus = new ArrayList<>();
            for (Integer integer : orderStatusArray) {
                orderStatus.add(integer);
            }
            criteria.andOrderStatusIn(orderStatus);
        }


        orderExample.setOrderByClause(sort +" "+order );  // order by add_time desc
        List<Order> orders = orderMapper.selectByExample(orderExample);
        List<OrderVo>  orderVos = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Order order1 : orders) {
            OrderVo tempOrderVo = new OrderVo(
                    order1.getId(),
                    order1.getUserId(),
                    order1.getOrderSn(),
                    order1.getOrderStatus(),
                    order1.getConsignee(),
                    order1.getMobile(),
                    order1.getAddress(),
                    order1.getMessage(),
                    order1.getGoodsPrice().intValue(),
                    order1.getFreightPrice().intValue(),
                    order1.getCouponPrice().intValue(),
                    order1.getIntegralPrice().intValue(),
                    order1.getGrouponPrice().intValue(),
                    order1.getOrderPrice().intValue(),
                    order1.getActualPrice().intValue(),
                    order1.getComments(),
                    order1.getEndTime()==null?null:simpleDateFormat.format(order1.getEndTime()),
                    order1.getAddTime()==null?null:simpleDateFormat.format(order1.getAddTime()),
                    order1.getUpdateTime()==null?null:simpleDateFormat.format(order1.getUpdateTime()),
                    order1.getDeleted()

            );
            orderVos.add(tempOrderVo);
        }
//        查看订单总数
        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        int size = orderPageInfo.getSize();

        OrderListVo orderListVo = new OrderListVo();
        orderListVo.setItems(orderVos);
        orderListVo.setTotal(size);

        return orderListVo;
    }
    /**  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   for (OrderGoods orderGood : orderGoods) {
       OrderGoodsVo tempOrderGoodsVo = new OrderGoodsVo(
               orderGood.getId(),
               orderGood.getOrderId(),
               orderGood.getGoodsId(),
               orderGood.getGoodsName(),
               orderGood.getGoodsSn(),
               orderGood.getProductId(),
               orderGood.getNumber().intValue(),
               orderGood.getPrice().intValue(),
               orderGood.getSpecifications(),
               orderGood.getPicUrl(),
               orderGood.getComment(),
               orderGood.getAddTime()==null? null:simpleDateFormat.format(orderGood.getAddTime()),
               orderGood.getUpdateTime() ==null?null:simpleDateFormat.format(orderGood.getUpdateTime()),
               false
       );
       orderGoodsVos.add(tempOrderGoodsVo);

   }
   */
    @Override
    public OrderDetailVo getDetailId(Integer id) { //id为订单id
//        获取  List<OrderGoodsVo> orderGoodsVos
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(id);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

//        获取Order
        Order order = orderMapper.selectByPrimaryKey(id);
//      获取user
        OrderDetailUserVo detailUserVo = new OrderDetailUserVo();
        User user = userMapper.selectByPrimaryKey(order.getUserId());
        detailUserVo.setNickname(user.getNickname());
        detailUserVo.setAvatar(user.getAvatar());
        OrderDetailVo orderDetailVo = new OrderDetailVo(orderGoods, detailUserVo, order);
        return orderDetailVo;
    }

    @Override
    public void refund(Integer orderId, Integer refundMoney) {


        Order order = orderMapper.selectByPrimaryKey(orderId);
        //已退款状态 --> 203
        order.setOrderStatus(Short.valueOf("203"));
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public void ship(Integer orderId, String shipChannel, String shipSn) {

        Order order = orderMapper.selectByPrimaryKey(orderId);
        //已发货状态 --> 301
        order.setOrderStatus(Short.valueOf("301"));
        order.setShipChannel(shipChannel);
        order.setShipSn(shipSn);
        orderMapper.updateByPrimaryKeySelective(order);
    }


    /**
     * 获得特定用户的特定订单列表 通过showType和UserId
     * @param showType 0:所有，1待付款101，2代发货201，3待收货301，4待评价401和402
     *
     */

    @Override
    public Map<String, Object> queryOrder(Integer page, Integer size, Integer userId, Integer showType) {

        PageHelper.startPage(page,size);
        Map<String,Object> orderList = new HashMap<>();

        if(showType == 0){
            List<Map<String,Object>> data = new ArrayList<>();
            Map<String,Object> dataMap = new HashMap<>();
            OrderExample orderExample = new OrderExample();
            orderExample.setOrderByClause("update_time desc");
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
            String orderStatusText;

            //拿到所有订单
            List<Order> orders = orderMapper.selectByExample(orderExample);
            WxOrderStatusUtils wxOrderStatusUtils = new WxOrderStatusUtils();


            //遍历订单，拿到每个订单包含的商品的list，
            for (Order order : orders) {
                OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
                OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
                criteria1.andOrderIdEqualTo(order.getId());
                List<OrderGoods> ordersGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
                List<Map<String, Object>> goodsList = new ArrayList<>();

                //获得每个单个商品的数据，然后将他们装入列表中
                for (OrderGoods good : ordersGoods) {
                    Map<String, Object> orderGood = new HashMap<>();
                    orderGood.put("goodsName", good.getGoodsName());
                    orderGood.put("id", good.getId());
                    orderGood.put("number", good.getNumber());
                    orderGood.put("picUrl", good.getPicUrl());
                    goodsList.add(orderGood);
                }

                dataMap.put("actualPrice", order.getActualPrice());
                dataMap.put("goodsList", goodsList);



                WxOrderStatusUtils wxOrderStatusUtils1 = wxOrderStatusUtils.handleOption(order.getOrderStatus());
                if(order.getComments()<=0){
                    wxOrderStatusUtils1.setComment(false);
                }

                dataMap.put("handleOption", wxOrderStatusUtils1);
                dataMap.put("id", order.getId());
                dataMap.put("isGroupin", false);
                dataMap.put("orderSn", order.getOrderSn());

                orderStatusText = wxOrderStatusUtils.orderStatus(order.getOrderStatus());
                dataMap.put("orderStatusText", orderStatusText);
                data.add(dataMap);
                dataMap = new HashMap<>();

            }

            orderList.put("count",orders.size());
            orderList.put("data",data);
            double totalPages = (double) (orders.size() / size);
            if(orders.size()<=10){
                totalPages = 1;
            }
            orderList.put("totalPages",Math.ceil(totalPages));
            return orderList;
        }
        if(showType == 1){
            List<Map<String,Object>> data = new ArrayList<>();
            Map<String,Object> dataMap = new HashMap<>();
            OrderExample orderExample = new OrderExample();
            orderExample.setOrderByClause("update_time desc");
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andOrderStatusEqualTo((short) 101).andDeletedEqualTo(false);

            //拿到所有订单
            List<Order> orders = orderMapper.selectByExample(orderExample);


            WxOrderStatusUtils wxOrderStatusUtils = new WxOrderStatusUtils();


            //遍历订单，拿到每个订单包含的商品的list，
            for (Order order : orders) {
                OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
                OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
                criteria1.andOrderIdEqualTo(order.getId());
                List<OrderGoods> ordersGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
                List<Map<String, Object>> goodsList = new ArrayList<>();


                //获得每个单个商品的数据，然后将他们装入列表中
                for (OrderGoods good : ordersGoods) {
                    Map<String, Object> orderGood = new HashMap<>();
                    orderGood.put("goodsName", good.getGoodsName());
                    orderGood.put("id", good.getId());
                    orderGood.put("number", good.getNumber());
                    orderGood.put("picUrl", good.getPicUrl());
                    goodsList.add(orderGood);
                }

                dataMap.put("actualPrice", order.getActualPrice());
                dataMap.put("goodsList", goodsList);

                dataMap.put("handleOption", wxOrderStatusUtils.handleOption((short) 101));
                dataMap.put("id", order.getId());
                dataMap.put("isGroupin", false);
                dataMap.put("orderSn", order.getOrderSn());

                dataMap.put("orderStatusText","未付款");
                data.add(dataMap);
                dataMap = new HashMap<>();
            }

            orderList.put("count",orders.size());
            orderList.put("data",data);
            double totalPages = (double) (orders.size() / size);
            if(orders.size()<=10){
                totalPages = 1;
            }
            orderList.put("totalPages",Math.ceil(totalPages));
            return orderList;
        }
        if(showType == 2){
            List<Map<String,Object>> data = new ArrayList<>();
            Map<String,Object> dataMap = new HashMap<>();
            OrderExample orderExample = new OrderExample();
            orderExample.setOrderByClause("update_time desc");
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andOrderStatusEqualTo((short) 201).andDeletedEqualTo(false);

            //拿到所有订单
            List<Order> orders = orderMapper.selectByExample(orderExample);


            WxOrderStatusUtils wxOrderStatusUtils = new WxOrderStatusUtils();


            //遍历订单，拿到每个订单包含的商品的list，
            for (Order order : orders) {
                OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
                OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
                criteria1.andOrderIdEqualTo(order.getId());
                List<OrderGoods> ordersGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
                List<Map<String, Object>> goodsList = new ArrayList<>();


                //获得每个单个商品的数据，然后将他们装入列表中
                for (OrderGoods good : ordersGoods) {
                    Map<String, Object> orderGood = new HashMap<>();
                    orderGood.put("goodsName", good.getGoodsName());
                    orderGood.put("id", good.getId());
                    orderGood.put("number", good.getNumber());
                    orderGood.put("picUrl", good.getPicUrl());
                    goodsList.add(orderGood);
                }

                dataMap.put("actualPrice", order.getActualPrice());
                dataMap.put("goodsList", goodsList);


                dataMap.put("handleOption", wxOrderStatusUtils.handleOption((short) 201));
                dataMap.put("id", order.getId());
                dataMap.put("isGroupin", false);
                dataMap.put("orderSn", order.getOrderSn());

                dataMap.put("orderStatusText","待发货");
                data.add(dataMap);
                dataMap = new HashMap<>();
            }

            orderList.put("count",orders.size());
            orderList.put("data",data);
            double totalPages = (double) (orders.size() / size);
            if(orders.size()<=10){
                totalPages = 1;
            }
            orderList.put("totalPages",Math.ceil(totalPages));
            return orderList;
        }
        if(showType == 3){
            List<Map<String,Object>> data = new ArrayList<>();
            Map<String,Object> dataMap = new HashMap<>();
            OrderExample orderExample = new OrderExample();
            orderExample.setOrderByClause("update_time desc");
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andOrderStatusEqualTo((short) 301).andDeletedEqualTo(false);

            //拿到所有订单
            List<Order> orders = orderMapper.selectByExample(orderExample);


            String orderStatusText = null;

            //遍历订单，拿到每个订单包含的商品的list，
            for (Order order : orders) {
                OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
                OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
                criteria1.andOrderIdEqualTo(order.getId());
                List<OrderGoods> ordersGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
                List<Map<String, Object>> goodsList = new ArrayList<>();
                WxOrderStatusUtils wxOrderStatusUtils = new WxOrderStatusUtils();

                //获得每个单个商品的数据，然后将他们装入列表中
                for (OrderGoods good : ordersGoods) {
                    Map<String, Object> orderGood = new HashMap<>();
                    orderGood.put("goodsName", good.getGoodsName());
                    orderGood.put("id", good.getId());
                    orderGood.put("number", good.getNumber());
                    orderGood.put("picUrl", good.getPicUrl());
                    goodsList.add(orderGood);
                }

                dataMap.put("actualPrice", order.getActualPrice());
                dataMap.put("goodsList", goodsList);

                dataMap.put("handleOption", wxOrderStatusUtils.handleOption((short) 301));
                dataMap.put("id", order.getId());
                dataMap.put("isGroupin", false);
                dataMap.put("orderSn", order.getOrderSn());

                dataMap.put("orderStatusText","已发货");
                data.add(dataMap);
                dataMap = new HashMap<>();
            }

            orderList.put("count",orders.size());
            orderList.put("data",data);
            double totalPages = (double) (orders.size() / size);
            if(orders.size()<=10){
                totalPages = 1;
            }
            orderList.put("totalPages",Math.ceil(totalPages));
            return orderList;
        }
        if(showType == 4){
            List<Map<String,Object>> data = new ArrayList<>();
            Map<String,Object> dataMap = new HashMap<>();
            OrderExample orderExample = new OrderExample();
            orderExample.setOrderByClause("update_time desc");
            OrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andOrderStatusBetween((short)400,(short)403).andDeletedEqualTo(false).andCommentsGreaterThan((short) 0);

            //拿到所有订单
            List<Order> orders = orderMapper.selectByExample(orderExample);

            WxOrderStatusUtils wxOrderStatusUtils = new WxOrderStatusUtils();


            //遍历订单，拿到每个订单包含的商品的list，
            for (Order order : orders) {
                OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
                OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
                criteria1.andOrderIdEqualTo(order.getId());
                List<OrderGoods> ordersGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
                List<Map<String, Object>> goodsList = new ArrayList<>();


                //获得每个单个商品的数据，然后将他们装入列表中
                for (OrderGoods good : ordersGoods) {
                    Map<String, Object> orderGood = new HashMap<>();
                    orderGood.put("goodsName", good.getGoodsName());
                    orderGood.put("id", good.getId());
                    orderGood.put("number", good.getNumber());
                    orderGood.put("picUrl", good.getPicUrl());
                    goodsList.add(orderGood);
                }

                dataMap.put("actualPrice", order.getActualPrice());
                dataMap.put("goodsList", goodsList);

                WxOrderStatusUtils wxOrderStatusUtils1 = wxOrderStatusUtils.handleOption((short) 401);
                if(order.getComments()==0){
                    wxOrderStatusUtils1.setComment(false);
                }

                dataMap.put("handleOption", wxOrderStatusUtils1);
                dataMap.put("id", order.getId());
                dataMap.put("isGroupin", false);
                dataMap.put("orderSn", order.getOrderSn());

                dataMap.put("orderStatusText","已收货");
                data.add(dataMap);
                dataMap = new HashMap<>();
            }

            orderList.put("count",orders.size());
            orderList.put("data",data);
            double totalPages = (double) (orders.size() / size);
            if(orders.size()<=10){
                totalPages = 1;
            }
            orderList.put("totalPages",Math.ceil(totalPages));
            return orderList;
        }
        return null;
    }

    @Override
    public List<OrderGoods> queryOrderGoods(Integer orderId) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        return orderGoodsMapper.selectByExample(orderGoodsExample);
    }

    @Override
    public OrderGoods queryOrderGoodsSingle(Integer orderId, Integer goodsId) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        return orderGoods.get(0);
    }


/**
 * 提交评论→更新评论表，更新order，orderGoods，comment
 * order       `comments` smallint(6) DEFAULT '0' COMMENT '待评价订单商品数量',
 *             `update_time` datetime DEFAULT NULL COMMENT '更新时间',
 *
 * orderGoods  `comment` int(11) DEFAULT '0' COMMENT '订单商品评论，如果是-1，则超期不能评价；
 *                                                               如果是0，则可以评价；
 *                                                               如果其他值，则是comment表里面的评论ID。'
 *             `update_time` datetime DEFAULT NULL COMMENT '更新时间',
 */

    @Override
    public void orderCommentUpdate(Integer userId, String content, Boolean hasPicture, Integer orderGoodsId, List<String> picUrls, Short star) {
        GoodsComment goodsComment = new GoodsComment();
        goodsComment.setValueId(orderGoodsId);
        goodsComment.setType((byte) 0);
        goodsComment.setContent(content);
        goodsComment.setUserId(userId);
        goodsComment.setHasPicture(hasPicture);
        goodsComment.setPicUrls(picUrls.toArray(new String[]{}));
        goodsComment.setStar(star);
        goodsComment.setAddTime(new Date());
        goodsComment.setUpdateTime(new Date());

        goodsCommentMapper.insert(goodsComment);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andIdEqualTo(orderGoodsId).andDeletedEqualTo(false);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        orderGoods.get(0).setComment(goodsComment.getId());
        orderGoods.get(0).setUpdateTime(new Date());
        orderGoodsMapper.updateByExample(orderGoods.get(0),orderGoodsExample);

        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria1 = orderExample.createCriteria();
        criteria1.andUserIdEqualTo(userId).andIdEqualTo(orderGoods.get(0).getOrderId());
        List<Order> orders = orderMapper.selectByExample(orderExample);
        int comments = orders.get(0).getComments();
        comments = comments - 1;
        orders.get(0).setComments((short) comments);
        orderMapper.updateByExampleSelective(orders.get(0),orderExample);

    }

    @Override
    public List<Order> queryOrderDetail(Integer orderId) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        return orderMapper.selectByExample(orderExample);
    }


    /**
     * 设置订单取消状态；
     * 商品库存；
     * 优惠券；算了不还了。
     */

    @Override
    public void orderCancel(Integer orderId, Short orderStatus) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);

        List<Order> orders = orderMapper.selectByExample(orderExample);
        Order order = orders.get(0);
        order.setOrderStatus(orderStatus);
        order.setUpdateTime(new Date());

        orderMapper.updateByExampleSelective(order,orderExample);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
        criteria1.andOrderIdEqualTo(orderId);

        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (OrderGoods orderGood : orderGoods) {
            orderGood.setUpdateTime(new Date());
            Integer productId = orderGood.getProductId();
            Short number = orderGood.getNumber();

            GoodsProductExample goodsProductExample = new GoodsProductExample();
            GoodsProductExample.Criteria criteria2 = goodsProductExample.createCriteria();
            criteria2.andIdEqualTo(productId);
            List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
            Integer number1 = goodsProducts.get(0).getNumber() + number;
            goodsProducts.get(0).setNumber(number1);
            goodsProductMapper.updateByExampleSelective(goodsProducts.get(0),goodsProductExample);
            orderGoodsMapper.updateByExample(orderGood,orderGoodsExample);
        }

    }


    /**
     /**
     * 提交订单
     * 1. 创建订单和订单商品;
     * 2. 购物车
     * 3. 优惠券已用;
     * 4. 商品货品库存
     *
     */

    @Override
    public Integer orderSubmit(Integer addressId, Integer cartId, Integer couponId, String message, Integer userId) {

        if(addressId == null || cartId == null || userId == null){
            return null;
        }

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        if(cartId != 0){
            criteria.andIdEqualTo(cartId);
        }
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria1 = addressExample.createCriteria();
        criteria1.andIdEqualTo(addressId).andDeletedEqualTo(false);
        List<Address> addresses = addressMapper.selectByExample(addressExample);


        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria2 = couponExample.createCriteria();
        criteria2.andIdEqualTo(couponId).andDeletedEqualTo(false);
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);

        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria3 = couponUserExample.createCriteria();
        criteria3.andCouponIdEqualTo(couponId).andUserIdEqualTo(userId);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);


        Order order = new Order();
        order.setUserId(userId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        order.setOrderSn(simpleDateFormat.format(new Date()));
        order.setOrderStatus((short) 101);
        order.setConsignee(addresses.get(0).getName());
        order.setMobile(addresses.get(0).getMobile());
        order.setAddress(addresses.get(0).getAddress());
        order.setMessage(message);
        order.setDeleted(false);

        String expressMin = orderMapper.selectSystemExpress("cskaoyan_mall_express_freight_min");
        String expressValue = orderMapper.selectSystemExpress("cskaoyan_mall_express_freight_value");
        int min = Integer.parseInt(expressMin);
        int value = Integer.parseInt(expressValue);


        BigDecimal price = new BigDecimal(0.0);
        for (Cart cart : carts) {
            price = price.add(cart.getPrice());
        }
        order.setGoodsPrice(price);
        if(price.compareTo(BigDecimal.valueOf((double) min)) > -1){
            order.setFreightPrice(BigDecimal.valueOf(0));
        }else{
            order.setFreightPrice(BigDecimal.valueOf(value));
        }
        if(couponId == 0){
            order.setCouponPrice(BigDecimal.valueOf(0));
        }else{
            BigDecimal discount = new BigDecimal(0.0);
            for (Coupon coupon : coupons) {
                discount = discount.add(coupon.getDiscount());
            }
            order.setCouponPrice(discount);
        }
        order.setIntegralPrice(BigDecimal.valueOf(0));
        order.setGrouponPrice(BigDecimal.valueOf(0));

        BigDecimal orderPrice = order.getGoodsPrice().add(order.getFreightPrice()).subtract(order.getCouponPrice());


        order.setOrderPrice(orderPrice);
        order.setActualPrice(orderPrice);
        order.setComments((short) carts.size());

        Date date = new Date();
        order.setAddTime(date);
        order.setUpdateTime(date);
        Date afterHour = new Date(date.getTime() + 2600000);
        order.setEndTime(afterHour);

        //插入新order
        orderMapper.insert(order);

        //插入新orderGood,删除购物车对应的商品,修改商品库存
        for (Cart cart : carts) {

            OrderGoods orderGood = new OrderGoods();
            orderGood.setOrderId(order.getId());
            orderGood.setGoodsId(cart.getGoodsId());
            orderGood.setGoodsName(cart.getGoodsName());
            orderGood.setGoodsSn(cart.getGoodsSn());
            orderGood.setProductId(cart.getProductId());
            orderGood.setNumber(cart.getNumber());
            orderGood.setPrice(cart.getPrice());
            orderGood.setSpecifications(cart.getSpecifications());
            orderGood.setPicUrl(cart.getPicUrl());
            orderGood.setComment(0);
            orderGood.setAddTime(new Date());
            orderGood.setUpdateTime(new Date());
            orderGood.setDeleted(false);

            cart.setId(null);
            cart.setDeleted(true);
            cartMapper.updateByExampleSelective(cart,cartExample);


            GoodsProductExample goodsProductExample = new GoodsProductExample();
            GoodsProductExample.Criteria criteria4 = goodsProductExample.createCriteria();
            criteria4.andIdEqualTo(cart.getProductId()).andDeletedEqualTo(false);
            List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
            Integer number = goodsProducts.get(0).getNumber();
            //下单时最后一件商品被售出，取消订单
            if(number <= 0 ){
                order.setDeleted(true);
                OrderExample orderExample = new OrderExample();
                OrderExample.Criteria criteria5 = orderExample.createCriteria();
                criteria5.andIdEqualTo(order.getId());
                orderMapper.updateByExampleSelective(order,orderExample);
                return null;
            }
            number = number - cart.getNumber();
            goodsProducts.get(0).setNumber(number);

            orderGoodsMapper.insert(orderGood);
            goodsProductMapper.updateByExampleSelective(goodsProducts.get(0),goodsProductExample);
        }



        //修改用户优惠券状态
        for (CouponUser couponUser : couponUsers) {
            couponUser.setStatus((short) 1);
            couponUser.setOrderId(order.getId());
            couponUser.setUpdateTime(new Date());
            couponUserMapper.updateByExample(couponUser,couponUserExample);
        }

        return order.getId();
    }

    @Override
    public void orderStatusUpdate(Integer orderId, Short orderStatus) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);

        List<Order> orders = orderMapper.selectByExample(orderExample);
        Order order = orders.get(0);
        order.setOrderStatus(orderStatus);
        order.setUpdateTime(new Date());
        if(orderStatus == 401){
            order.setConfirmTime((new Date()));
        }

        orderMapper.updateByExampleSelective(order,orderExample);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
        criteria1.andOrderIdEqualTo(orderId);

        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (OrderGoods orderGood : orderGoods) {
            orderGood.setUpdateTime(new Date());
            orderGoodsMapper.updateByExample(orderGood,orderGoodsExample);
        }

    }

    @Override
    public void orderDelete(Integer orderId) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);

        List<Order> orders = orderMapper.selectByExample(orderExample);
        Order order = orders.get(0);
        order.setDeleted(true);
        order.setUpdateTime(new Date());

        orderMapper.updateByExampleSelective(order,orderExample);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
        criteria1.andOrderIdEqualTo(orderId);

        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (OrderGoods orderGood : orderGoods) {
            orderGood.setUpdateTime(new Date());
            orderGood.setDeleted(true);
            orderGoodsMapper.updateByExample(orderGood,orderGoodsExample);
        }

    }

}


